package pony.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pony.model.Calculator;

/**
 * Servlet implementation class CalcServlet
 */
@WebServlet("/CalcServlet")
public class CalcServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CalcServlet() {
        super();
    }

	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int inputNum1 = Integer.parseInt(request.getParameter("inputNum1"));
		int inputNum2 = Integer.parseInt(request.getParameter("inputNum2"));
		int result = 0;
		
		String action = request.getParameter("action");
		Calculator calculator = new Calculator();
		
		if(action.equals("add")) {
			result = calculator.add(inputNum1, inputNum2);
		} else if(action.equals("minus")) {
			result = calculator.minus(inputNum1, inputNum2);
		} else if(action.equals("multiplication")) {
			result = calculator.multiplication(inputNum1, inputNum2);
		} else if(action.equals("division")) {
			result = calculator.division(inputNum1, inputNum2);
		}
		
		Integer calcResult = new Integer(result);
		Integer number1 = new Integer(inputNum1);
		Integer number2 = new Integer(inputNum2);
		
		request.setAttribute("calcResult", calcResult);
		request.setAttribute("inputNum1", number1);
		request.setAttribute("inputNum2", number2);
		RequestDispatcher dispatcher = request.getRequestDispatcher("./JSPs/resultForCalc.jsp");
		if(dispatcher == null) {
			PrintWriter out = response.getWriter();
			out.println("I'm null!");
		}
		dispatcher.forward(request, response);
		
	}

}
